#include "postmanagerapi.h"

PostManagerApi::PostManagerApi(QObject *parent)
    : QObject{parent}
{
    baseUrl = Config::baseUrl;
    manager = new QNetworkAccessManager(0);
    request.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json"));//post请求设置为json，才能发送josn格式文件
    request.setRawHeader("Authorization",  qApp->property("token").value<QString>().toLocal8Bit());
}

QByteArray *PostManagerApi::getList(int pageNum, int pageSize, QString postCode,
                                          QString postName, QString status)
{
    QString params = "system/post/list?pageNum="+ QString::number(pageNum) +
                     "&pageSize=" + QString::number(pageSize);
    if(!postCode.isEmpty()){
        params += "&postCode=" + postCode;
    }
    if(!postName.isEmpty()){
        params += "&postName=" + postName;
    }
    if(!status.isEmpty()){
        params += "&status=" + status;
    }
    request.setUrl(QUrl(baseUrl + params));
    QNetworkReply* reply = manager->get(request);
    //同步请求
    QEventLoop eventLoop;
    connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();
    data = new QByteArray(reply->readAll().data());
    reply->deleteLater();
    utils.requestCheck(data);
    return data;
}

QByteArray *PostManagerApi::editPost(int id, Post &post)
{
    QString params = "system/post";
    QByteArray arr = QJsonDocument(post.toJsonObject()).toJson();
    request.setUrl(QUrl(baseUrl + params));
    QNetworkReply* reply;
    if(id > 0){
        reply = manager->put(request,arr);
    }else{
        reply = manager->post(request,arr);
    }
    //同步请求
    QEventLoop eventLoop;
    connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();
    data = new QByteArray(reply->readAll().data());
    reply->deleteLater();
    utils.requestCheck(data);
    return data;
}

QByteArray *PostManagerApi::deleteItems(QString ids)
{
    request.setUrl(baseUrl + "system/post/" + ids);
    QNetworkReply * r = manager->deleteResource(request);
    //同步请求
    QEventLoop eventLoop;
    connect(r, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();
    data = new QByteArray(r->readAll().data());
    r->deleteLater();
    utils.requestCheck(data);
    return data;
}

QByteArray *PostManagerApi::getById(int id)
{
    request.setUrl(baseUrl + "system/post/" + QString::number(id));
    QNetworkReply * r = manager->get(request);
    //同步请求
    QEventLoop eventLoop;
    connect(r, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();
    data = new QByteArray(r->readAll().data());
    r->deleteLater();
    utils.requestCheck(data);
    return data;
}

